/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package me.everdras.WordFilter;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.LinkedList;
import org.bukkit.ChatColor;

/**
 *
 * @author Josh
 */
public class WordFilter extends JavaPlugin {
    public static final File listpath = new File("plugins" + File.separator + "WordFilter" + File.separator + " WordFiltConfig.ser");
    public static final File optionpath = new File("plugins" + File.separator + "WordFilter" + File.separator + " WordFiltOption.ser");
    public static final File dir = new File("plugins" + File.separator + "WordFilter" + File.separator);
    private WFPlayerListener playerlistener;
    private static final Logger log = Logger.getLogger("Minecraft");
    private boolean activated;
    private ArrayList<FilteredWord> words;
    private FilterOption option;
    
    
    @Override
    public void onEnable()
    {
        loadWords();
        PluginManager pm = getServer().getPluginManager();
        
        Porter port = new Porter(optionpath.getPath());
        
        Object inputed = null;
        if(port.primeInput()) {
            inputed = port.input();
        }
        
        if(inputed != null)
            option = (FilterOption) inputed;
        else
            option = FilterOption.REPLACE_ALL;
        
        words = this.getWords();
        
        playerlistener = new WFPlayerListener(this);
        
        pm.registerEvent(org.bukkit.event.Event.Type.PLAYER_CHAT, playerlistener, org.bukkit.event.Event.Priority.Highest, this);
        
        PluginDescriptionFile pdf = getDescription();
        
        activated = true;
        
        log.info("WordFilter plugin loaded.");
        
    }

    @Override
    public void onDisable()
    {
        log.info("WordFilter is saving word lists...");
        Porter port = new Porter(listpath.getPath());
        if(!dir.exists()) {
            try {
                dir.mkdir();
            } catch (Exception ex) {
                log.log(Level.SEVERE, "Unable to create word list directory- words will not save.");
            }
        }
        
        if(!listpath.exists()) {
            try {
                listpath.createNewFile();
            } catch (IOException ex) {
                log.log(Level.SEVERE, "Unable to create word list flat file- words will not save.");
            }
        }
        
        if(port.primeOutput()) {
            port.output(words);
            port.close();
            log.info("WordFilter lists saved.");
        }
        
        if(!optionpath.exists()) {
            try {
                optionpath.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger("Minecraft").log(Level.SEVERE, null, ex);
            }
        }
        
        port.close();
        
        port = new Porter(optionpath.getPath());
        
        if(port.primeOutput()) {
            port.output(option);
        }
        port.close();
        
        
        
        log.info("WordFilter disabled");
    }
    
    
    public ArrayList<FilteredWord> getWords() {
        return words;
    }
    
    private void loadWords() {
        
        if(!dir.exists()) {
            try {
                dir.mkdir();
            } catch (Exception ex) {
                log.log(Level.SEVERE, "Unable to create word list directory- words will not save.");
            }
        }
        
        if(!listpath.exists()) {
            try {
                listpath.createNewFile();
            } catch (IOException ex) {
                log.log(Level.SEVERE, "Unable to create word list flat file- words will not save.");
            }
        }
        
        Porter port = new Porter(listpath.getPath());
        try {
            if(port.primeInput()) {
                words = (ArrayList<FilteredWord>) port.input();
                port.close();
            }
        }
        catch(Exception e) {
            loadWordsListFromOldFormat();
        }
        
        if(words == null) {
            
            loadWordsListFromOldFormat();
            
        }
        
        if(words == null) {
            words = new ArrayList<FilteredWord>();
        }
    }
    
    
    
    
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
        String name;
        if(sender instanceof Player) {
            name = ((Player)sender).getName();
        }
        else
            name = "Server";
	if(cmd.getName().equalsIgnoreCase("wf")){
            if(args.length < 1)
                return false;
            
		if(args[0].equalsIgnoreCase("add")) {
                    if(!hasPermission(sender, "WordFilter.add")) {
                        sender.sendMessage("Insufficient permissions.");
						return true;
                    }
                    
                        
                    try {

                        if(isAlreadyFiltering(args[1])) {
                            sender.sendMessage("That word is already being filtered!");
                            return true;
                        }
                        words.add(new FilteredWord(args[1], args[2]));
                        sender.sendMessage("Added word.");
                        log.info("WF:" + name + " added " + args[1] + "|" + args[2] + " to the list");
                    }
                    catch(Exception e) {
                        sender.sendMessage("/wf add originalword replacementword");
                    }
                    
                }
                else if(args[0].equalsIgnoreCase("remove")) {
                    if(!hasPermission(sender, "WordFilter.remove")) {
                        sender.sendMessage("Insufficient permissions.");
						return true;
                    }
                    
                    try {
                        if(words.remove(new FilteredWord(args[1], args[2]))) {
                            sender.sendMessage("Removed word.");
                            log.info("WF:" + name + " removed " + args[1] + "|" + args[2] + " from the list");
                        }
                        else
                            sender.sendMessage("Word not found- could not remove.");

                    }
                    catch(Exception e) {
                        sender.sendMessage("/wf remove originalword replacementword");
                    }
                    
                }
                else if(args[0].equalsIgnoreCase("on")) {
                    if(!hasPermission(sender, "WordFilter.toggle")) {
                        sender.sendMessage("Insufficient permissions.");
						return true;
                    }
                    
                    activated = true;
                    sender.sendMessage("WF turned on.");
                    log.info("WF:" + name + " turned the filter on.");
                   
                }
                else if(args[0].equalsIgnoreCase("off")) {
                    if(!hasPermission(sender, "WordFilter.toggle")) {
                        sender.sendMessage("Insufficient permissions.");
						return true;
                    }
                    
                    activated = false;
                    sender.sendMessage("WF turned off.");
                    log.info("WF:" + name + " turned the filter off.");
                    
                }
                else if(args[0].equalsIgnoreCase("list")) {
                    if(!hasPermission(sender, "WordFilter.list")) {
                        sender.sendMessage("Insufficient permissions.");
						return true;
                    }
                    
                    if(args.length < 2) {
                        printWordList(sender, "1");
                    }
                    else {
                        printWordList(sender, args[1]);
                    }
                    return true;
                    
                }
                else if(args[0].equalsIgnoreCase("clear")) {
                    if(!hasPermission(sender, "WordFilter.remove")) {
                        sender.sendMessage("Insufficient permissions.");
						return true;
                    }
                    
                    words = new ArrayList<FilteredWord>();
                    playerlistener.setWords(words);
                    sender.sendMessage("WF: List cleared.");
                    log.info("WF:" + name + " cleared the list.");
                    
                }
                else if(args[0].equals("option")) {
                    if(!hasPermission(sender, "WordFilter.options")) {
                        sender.sendMessage("Insufficient permissions.");
						return true;
                    }
					
					
                    if(args.length < 2) {
                        sender.sendMessage("/wf option REPLACE_ALL/REPLACE_PART/REPLACE_WORD");
                        return true;
                    }
                        
                    if(args[1].equalsIgnoreCase(FilterOption.REPLACE_ALL.toString())) {
                            option = FilterOption.REPLACE_ALL;
                            sender.sendMessage("Filter method set to ALL.");
                    }
                    else if(args[1].equalsIgnoreCase(FilterOption.REPLACE_WORD.toString())) {
                            option = FilterOption.REPLACE_WORD;
                            sender.sendMessage("Filter method set to WORD.");
                    }
                    else if(args[1].equalsIgnoreCase(FilterOption.REPLACE_PART.toString())) {
                            option = FilterOption.REPLACE_PART;
                            sender.sendMessage("Filter method set to PART.");
                    }
                    else
                        sender.sendMessage("/wf option REPLACE_ALL/REPLACE_PART/REPLACE_WORD");
                    
                    return true;
                }
                        
                        
                else {
                    sender.sendMessage("/wf clear|list|add|remove|on|off");
                    
                }
		return true;
                
	} 
	return false; 
    }
    
    public boolean isFiltering() {
        return activated;
    }
    
    private boolean isAlreadyFiltering(String checkme) {
        for(FilteredWord w : words) {
            if(w.getWord().equalsIgnoreCase(checkme))
                return true;
        }
        return false;
    }
    
    public FilterOption getMethod() {
        return option;
    }
    
    private void loadWordsListFromOldFormat() {
        Porter port = new Porter(listpath.getPath());
        
        LinkedList<FilteredWord> tempList;
        if(port.primeInput()) {
            tempList = (LinkedList<FilteredWord>)port.input();
        }
        else
            return;
        
        FilteredWord[] tempArr = new FilteredWord[tempList.size()];
        tempArr = tempList.toArray(tempArr);

        ArrayList<FilteredWord> tempArrList = new ArrayList<FilteredWord>();
        
        tempArrList.addAll(Arrays.asList(tempArr));
        
        words = tempArrList;
    }
    
    private void printWordList(CommandSender sender, String page) {
        String ret = "";
        int index;
        
        try {
            index = Integer.parseInt(page) - 1;
            index *= 7;
        }
        catch(Exception e) {
            sender.sendMessage("Error parsing page number.");
            return;
        }
        
        sender.sendMessage(ChatColor.AQUA + "List (Page " + page + "):");
        for(int i = index; i < words.size() && i < index+7; i++) {
            sender.sendMessage(ChatColor.DARK_RED + words.get(i).getWord() + ChatColor.BLACK + " | " + ChatColor.DARK_GREEN + words.get(i).getReplacement());
        }
        
        
    }
    
    private boolean hasPermission(CommandSender sender, String node) {
        return (sender.hasPermission(node) || sender.isOp() || !(sender instanceof Player));
    }
    
    
    
    
    
    
    
}

//modes: replace whole word, replace part of word, replace whole words only
